﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Translator
{
    public class TranslateService
    {
        private readonly string _apiKey;
        private readonly string _secretKey;
        private string _accessToken;
        private DateTime _tokenExpireTime;
        private readonly HttpClient _httpClient;

        public TranslateService(string apiKey, string secretKey)
        {
            _apiKey = apiKey;
            _secretKey = secretKey;
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(10);
        }

        public async Task<string> TranslateAsync(string text, string from, string to)
        {
            await RefreshTokenIfNeeded();

            var requestData = new
            {
                q = text,
                from = from,
                to = to
            };

            string url = $"https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token={_accessToken}";

            var content = new StringContent(
                JsonConvert.SerializeObject(requestData),
                Encoding.UTF8,
                "application/json");

            var response = await _httpClient.PostAsync(url, content);
            var result = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"API请求失败: {response.StatusCode}");
            }

            return ParseTranslationResult(result);
        }

        private async Task RefreshTokenIfNeeded()
        {
            if (string.IsNullOrEmpty(_accessToken) || DateTime.Now >= _tokenExpireTime)
            {
                string tokenUrl = $"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={_apiKey}&client_secret={_secretKey}";

                var response = await _httpClient.GetAsync(tokenUrl);
                var result = await response.Content.ReadAsStringAsync();

                var json = JObject.Parse(result);
                if (json["error"] != null)
                {
                    throw new Exception($"获取Token失败: {json["error_description"]}");
                }

                _accessToken = json["access_token"].ToString();
                _tokenExpireTime = DateTime.Now.AddSeconds(json["expires_in"].Value<int>());
            }
        }

        private string ParseTranslationResult(string json)
        {
            try
            {
                var result = JObject.Parse(json);

                if (result["error_code"] != null)
                {
                    throw new Exception($"翻译错误 {result["error_code"]}: {result["error_msg"]}");
                }

                var translation = result["result"]?["trans_result"]?[0]?["dst"];
                if (translation == null)
                {
                    throw new Exception("无效的API响应格式");
                }

                return translation.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception($"解析翻译结果失败: {ex.Message}");
            }
        }

    }
}
